<template>
  <div class="app-container">
    <SearchFilter size="medium" :maxShow="3" @search="handleQuery" @reset="resetQuery">
      <el-form :model="queryParams" label-position="right" label-width="70px" ref="queryForm">
        <el-row  :gutter="20">
          <el-col :span="7">
            <el-form-item label="组织名称" prop="deptName">
              <el-input
                v-model="queryParams.deptName"
                placeholder="请输入组织名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="组织编号" prop="deptCode">
              <el-input
                v-model="queryParams.deptCode"
                placeholder="请输入组织编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="负责人" prop="leader">
              <el-input
                v-model="queryParams.leader"
                placeholder="请输入负责人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="到期时间" prop="endDate">
              <el-date-picker
                v-model="queryParams.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择到期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </SearchFilter>

    <div class="content-container">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="1.5">
          <p class="header-title">组织列表</p>
        </el-col>
        <div>
          <el-col :span="1.5" v-if="ids.length">
            <el-button
              size="small"
              v-hasPermi="['system:dept:add']"
              @click="handleDelete"
            >批量禁用</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
            >添加组织</el-button>
          </el-col>
        </div>
      </el-row>
  
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        :cell-class-name="cellcb"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="judgeSelect" align="center" />
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="deptName" label="组织机构名称" min-width="200" align="center"></el-table-column>
        <el-table-column prop="deptCode" label="组织编号" min-width="200" align="center"></el-table-column>
        <el-table-column prop="img" label="图片" min-width="120" align="center">
          <template slot-scope="scope">
            <ImagePreview :src="scope.row.arrImg" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="负责人" min-width="120" align="center"></el-table-column>
        <el-table-column prop="phone" label="联系方式" min-width="120" align="center"></el-table-column>
        <el-table-column prop="endDate" label="到期时间" min-width="120" align="center"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" align="center"></el-table-column>
        <el-table-column label="操作" min-width="160" fixed="right" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <span
              type="text"
              class="text-text table-btn"
              @click="getRouterInfo(scope.row)"
            >查看</span>
            <span
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:dept:edit']"
              class="text-text table-btn"
            >编辑</span>
            <template v-if="scope.row.deptCode !== '91330183MA2KD9B04H'">
              <span
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:dept:status']"
                class="text-danger table-btn"
              >{{ scope.row.status === '1' ? '启用' : '禁用' }}</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" custom-class="dialog" :visible.sync="open" append-to-body :close-on-click-modal="false" width="740px">
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="组织机构名称" prop="deptName">
              <el-input v-model="form.deptName" :disabled="form.deptCode === '91330183MA2KD9B04H'" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="组织编号" prop="deptCode">
              <el-input v-model="form.deptCode" :disabled="form.deptCode === '91330183MA2KD9B04H'" placeholder="请输入组织编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="负责人联系方式" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入负责人联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="11">
            <el-form-item label="单位地址" prop="unitArea" class="areaUnit">
              <el-input v-model="form.unitArea" placeholder="请输入单位地址" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="到期时间" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片">
              <image-upload v-model="form.img"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件">
              <file-upload v-model="form.file"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listDept, getDept, delDept, stateDept, delDeptCount, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SearchFilter from '@/components/SearchFile'


var validateCode = (rule, value, callback) => {
  var reg = /^[A-Za-z0-9]{18}$/;
  if (value === '') {
    callback(new Error('组织编号是必填项！'))
  } else if (reg.test(value)) {
    callback()
  } else {
    callback(new Error("仅限输入18位大小写字母、数字！"))
  }
}

export default {
  name: "Dept",
  dicts: ['sys_normal_disable'],
  components: { Treeselect, SearchFilter },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      deptNames: [],
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptName: undefined,
        deptCode: undefined,
        leader: undefined,
        endDate: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        deptCode: [
          { required: true, validator: validateCode, trigger: "blur" }
        ],
        leader: [
          { required: true, message: '负责人不能为空', trigger: "blur" },
        ],
        phone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        unitArea: [
          { required: true, message: '单位地址不能为空', trigger: "blur" }
        ],
        endDate: [
          { required: true, message: '到期时间不能为空', trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.$nextTick(() => {
      this.getList();
    })
  },
  methods: {
    cellcb(row){
      if(row.row.deptCode === '91330183MA2KD9B04H' && row.columnIndex === 0){
        return "myCell"
      }
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept({...this.queryParams}).then(response => {
        response.rows.forEach(item => {
          if (item.img) {
            item.arrImg = []
            let arr = item.img.split(',')
            arr.forEach(key => {
              item.arrImg.push(process.env.VUE_APP_BASE_API + key)
            })
          }
        })
        this.deptList = this.handleTree(response.rows, "deptId");
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        deptCode: undefined,
        leader: undefined,
        phone: undefined,
        unitArea: undefined,
        email: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log(123)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.$refs.queryForm.handleReset()
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加组织";
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
        listDeptExcludeChild(row.deptId).then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
          if (this.deptOptions.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.deptOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 跳转详情 */
    getRouterInfo({deptId}) {
      this.$router.push("/system/deptQuery/" + deptId);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            // console.log(this.form)
            // let img = []
            // if (this.form.img) {
            //   let arr = this.form.img.split(',')
            //   arr.forEach(item => {
            //     img.push(item.split('=')[1])
            //   })
            // }
            // console.log(img)
            updateDept({...this.form}).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept({...this.form, parentId: 0}).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deptIds = row.deptId || this.ids;
      const deptName = row.deptName || this.deptNames;
      this.$modal.confirm(`是否确认${row.status === '1' ? '启用' : '禁用'}组织${deptName}的数据项与轨迹表？`).then(function() {
        return stateDept({deptId: deptIds});
      }).then((res) => {
        console.log(res)
        // this.delDeptCount({ deptId })
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deptId);
      this.deptNames = selection.map(item => item.deptName);
      // this.single = selection.length != 1;
      // this.multiple = !selection.length;
    },
    judgeSelect(row, index) {
      return row.deptCode !== '91330183MA2KD9B04H' // 返回true该行可选，返回false则不可选
    }
  }
};
</script>

<style lang="scss" scoped>
  .table-img {
    width: 50px;
    height: 50px;
    margin: 0;
  }
  ::v-deep .areaUnit {
    .el-input__suffix {
      top: 6px;
    }
  }
  ::v-deep .dialog {
    position: relative;
    height: 80% !important;
  }
  ::v-deep .myCell .cell{
    visibility: hidden;
  }
</style>
